package org.zachary.creditbusiness.common.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zachary.creditbusiness.hotel.entity.Ban;
import org.zachary.creditbusiness.hotel.mapper.BanMapper;
import org.zachary.creditbusiness.hotel.mapper.ReservationMapper;
import org.zachary.creditbusiness.hotel.entity.Reservation;
import org.zachary.creditbusiness.commodityandhouse.entity.HouseOrder;
import org.zachary.creditbusiness.commodityandhouse.mapper.HouseOrderMapper;
import org.zachary.creditbusiness.commodityandhouse.entity.CommodityOrder;
import org.zachary.creditbusiness.commodityandhouse.mapper.CommodityOrderMapper;

/**
 * 统一封禁服务
 * 用于检查用户是否支付完所有订单，以及管理封禁状态
 */
@Service
public class UnifiedBanService {

    @Autowired
    private BanMapper banMapper;

    @Autowired
    private HouseOrderMapper houseOrderMapper;

    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private CommodityOrderMapper commodityOrderMapper;

    /**
     * 检查用户是否被封禁
     * @param userId 用户ID
     * @return true表示被封禁，false表示未被封禁
     */
    public boolean isUserBanned(Long userId) {
        long banCount = banMapper.selectCount(
                new QueryWrapper<Ban>().eq("user_id", userId)
        );
        return banCount > 0;
    }

    /**
     * 检查用户是否可以恢复（即是否支付完所有订单）
     * @param userId 用户ID
     * @return 检查结果
     */
    public BanRecoveryResult checkRecoveryEligibility(Long userId) {
        BanRecoveryResult result = new BanRecoveryResult();
        result.setUserId(userId);
        result.setCanRecover(true);

        // 检查房屋订单
        QueryWrapper<HouseOrder> houseQuery = new QueryWrapper<>();
        houseQuery.eq("user_id", userId).eq("status", 0); // status=0表示未支付
        long unpaidHouseOrders = houseOrderMapper.selectCount(houseQuery);
        result.setUnpaidHouseOrders(unpaidHouseOrders);

        if (unpaidHouseOrders > 0) {
            result.setCanRecover(false);
            result.addReason("还有 " + unpaidHouseOrders + " 个未支付的房屋订单");
        }

        // 检查酒店订单
        QueryWrapper<Reservation> hotelQuery = new QueryWrapper<>();
        hotelQuery.eq("user_id", userId).eq("is_pay", 0); // is_pay=0表示未支付
        long unpaidHotelOrders = reservationMapper.selectCount(hotelQuery);
        result.setUnpaidHotelOrders(unpaidHotelOrders);

        if (unpaidHotelOrders > 0) {
            result.setCanRecover(false);
            result.addReason("还有 " + unpaidHotelOrders + " 个未支付的酒店订单");
        }

        // 检查商品订单
        QueryWrapper<CommodityOrder> commodityQuery = new QueryWrapper<>();
        commodityQuery.eq("user_id", userId).eq("finished", 1); // finished=1表示货到付款待支付
        long unpaidCommodityOrders = commodityOrderMapper.selectCount(commodityQuery);
        result.setUnpaidCommodityOrders(unpaidCommodityOrders);

        if (unpaidCommodityOrders > 0) {
            result.setCanRecover(false);
            result.addReason("还有 " + unpaidCommodityOrders + " 个未支付的商品订单");
        }

        return result;
    }

    /**
     * 恢复用户（删除所有封禁记录）
     * @param userId 用户ID
     * @return 删除的记录数
     */
    public int recoverUser(Long userId) {
        BanRecoveryResult eligibility = checkRecoveryEligibility(userId);
        if (!eligibility.isCanRecover()) {
            throw new IllegalStateException("用户 " + userId + " 不符合恢复条件: " +
                    String.join(", ", eligibility.getReasons()));
        }

        return banMapper.delete(
                new QueryWrapper<Ban>().eq("user_id", userId)
        );
    }

    /**
     * 封禁恢复结果类
     */
    public static class BanRecoveryResult {
        private Long userId;
        private boolean canRecover;
        private long unpaidHouseOrders;
        private long unpaidHotelOrders;
        private long unpaidCommodityOrders;
        private java.util.List<String> reasons = new java.util.ArrayList<>();

        public Long getUserId() {
            return userId;
        }

        public void setUserId(Long userId) {
            this.userId = userId;
        }

        public boolean isCanRecover() {
            return canRecover;
        }

        public void setCanRecover(boolean canRecover) {
            this.canRecover = canRecover;
        }

        public long getUnpaidHouseOrders() {
            return unpaidHouseOrders;
        }

        public void setUnpaidHouseOrders(long unpaidHouseOrders) {
            this.unpaidHouseOrders = unpaidHouseOrders;
        }

        public long getUnpaidHotelOrders() {
            return unpaidHotelOrders;
        }

        public void setUnpaidHotelOrders(long unpaidHotelOrders) {
            this.unpaidHotelOrders = unpaidHotelOrders;
        }

        public long getUnpaidCommodityOrders() {
            return unpaidCommodityOrders;
        }

        public void setUnpaidCommodityOrders(long unpaidCommodityOrders) {
            this.unpaidCommodityOrders = unpaidCommodityOrders;
        }

        public java.util.List<String> getReasons() {
            return reasons;
        }

        public void setReasons(java.util.List<String> reasons) {
            this.reasons = reasons;
        }

        public void addReason(String reason) {
            this.reasons.add(reason);
        }
    }
}